const request = require('request-promise');
const db = uniCloud.database();

// 发送hms消息
async function sendHmsMsg(tokenArr, desc) {
  let mTokenArr = []
  if (tokenArr && getObjType(tokenArr) == 'String') mTokenArr = [tokenArr]
  if (tokenArr && tokenArr.length && getObjType(tokenArr) == 'Array') mTokenArr = tokenArr
  if (!tokenArr && !tokenArr.length) return {msg: '参数为空'}
  let tokenRes = await getToken()
  //发送的消息保存到数据库
  let saveRes = await savePushDb(desc)
  console.log("saveRes===", saveRes)
  //开始推送消息
  let data = await pushMessage(saveRes, tokenRes.access_token, mTokenArr)
  if (tokenArr && tokenArr.length) data.tokenArr = mTokenArr
  //推送结果更新到数据库
  await updatePushDb(saveRes, data)
  return data
}

// 客户端收到消息
async function sendHmsMsgBack(pushId) {
  let result = await db.collection("hms-list").doc(pushId).update({
    backTimeId: new Date().getTime(),
  })
  return result
}

function getObjType(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1)
}

// 获取token
async function getToken() {
  const options = {
    method: 'POST',
    uri: "https://oauth-login.cloud.huawei.com/oauth2/v3/token",
    form: {
      grant_type: "client_credentials",
      client_id: "110591517",
      client_secret: 'a0506bfcbb550a332dedc5de882bf958c775b7baa0d8fdb97544ae95eb9b5959'
    },
    headers: {
      'content-type': 'application/x-www-form-urlencoded'
    }
  };
  let data = await getWebData(options)
  return data
}

// 推送消息
async function pushMessage(saveRes, access_token, tokenArr) {
  const options = {
    method: 'POST',
    json: true,
    url: "https://push-api.cloud.huawei.com/v1/110591517/messages:send",
    body: {
      "validate_only": false,
      "message": {
        "data": `{'pushId': ${saveRes.id}, 'param2': 'value2'}`,
        "token": tokenArr
      }
    },
    headers: {
      Authorization: `Bearer ${access_token}`
    }
  };
  let sendRes = await getWebData(options)
  return sendRes
}

// 保存推送数据到数据库------------
async function savePushDb(desc) {
  let result = await db.collection("hms-list").add({
    sendTimeId: new Date().getTime(),
    desc
  })
  return result
}

// 更新推送数据到数据库------------
async function updatePushDb(pushObj, data) {
  let result = await db.collection("hms-list").doc(pushObj.id).update({
    ...data
  })
  return result
}

async function getWebData(options) {
  return new Promise((resolve, reject) => {
    request(options).then(res => {
      if (typeof (res) == "string") res = JSON.parse(res)
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}

module.exports = {
  sendHmsMsg,
  sendHmsMsgBack,
};
